﻿@using XRM.Security.WebUI.MvcHelpers
@using XRM.Security.DataAccess.Enums
@using XRM.Security.WebUI.Security
@model XRM.Security.WebUI.Models.UserRegister.UserRegisterModel
@{
    ViewBag.Title = Model.IsEdit ? Model.FullName : "Добавление пользователя";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var returnUrl = Request.UrlReferrer == null || Request.HttpMethod == "POST" ? Url.Action("Index") : Html.Encode(Request.UrlReferrer.ToString());
}
@functions {

    readonly string[] userRoles = UserPrincipal.Current.Roles;
    private bool IsUserInRole(IEnumerable<string> roles)
    {
        return roles.Intersect(userRoles).Any();
    }
}
@section styles
{
    <style type="text/css">
        .tab-pane {
            min-height: 380px;
        }
    </style>
}
@Html.Partial("ReturnLinkPartial", new Tuple<string, string>(returnUrl, "Вернуться к списку пользователей"))

<div>
    <p class="buttonsDiv">
        <a href="@Url.Action("Edit", "Request", new {userId = Model.Id})" class="btn btn-primary">Создать заявку</a>
        <a href="@Url.Action("Index", "Request", new {text = Model.FullName})">Перейти к заявкам пользователя</a>
    </p>

    <ul class="nav nav-tabs" role="tablist" id="userTabs">
        <li id="liContactInfo" role="presentation" class="active"><a href="#divContactInfo" role="tab" data-toggle="tab">Контактная информация</a></li>
        <li id="liInfoSystem" role="presentation"><a href="#divInfoSystem" role="tab" data-toggle="tab">Информационные системы</a></li>
        <li id="liSczi" role="presentation"><a href="#divSczi" role="tab" data-toggle="tab">Информация об СКЗИ</a></li>
        @if (IsUserInRole(new[] { UserRoles.Administrator.ToString(), UserRoles.UsersReestrSkziEditor.ToString(), UserRoles.UsersReestrSertificateEditor.ToString() }))
        {
        <li id="liCert" role="presentation"><a href="#divCert" role="tab" data-toggle="tab">Информация о сертификатах</a></li>
        }
    </ul>
        
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="divContactInfo">
            @using (Html.BeginForm("Edit", "UserRegister", FormMethod.Post, new { @class = "form-horizontal", id = "formContactInfo" }))
            {      
                @Html.AntiForgeryToken()
                const string inputCss = "form-control";
                const string divCss = "col-sm-6";
                
                @Html.HiddenFor(m => m.Id)
                <div class="form-group">
                    @Html.LabelFor(m => m.LastName, new { @class = "control-label required" })
                    <div class="@divCss">
                        @Html.TextBoxFor(m => m.LastName, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.LastName)
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.FirstName, new { @class = "control-label required" })
                    <div class="@divCss">
                        @Html.TextBoxFor(m => m.FirstName, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.FirstName)
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.MotherName, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.TextBoxFor(m => m.MotherName, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.MotherName)
                    </div>
                </div>
        
                <div class="form-group">
                    @Html.LabelFor(m => m.DepartmentId, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.DropDownListFor(m => m.DepartmentId, Model.DepartmentAllList, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.DepartmentId)
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => m.Post, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.TextBoxFor(m => m.Post, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.Post)
                    </div>
                </div>
        
                <div class="form-group">
                    @Html.LabelFor(m => m.DepartmentAddressId, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.DropDownListFor(m => m.DepartmentAddressId, Model.DepartmentAddressAllList, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.DepartmentAddressId)
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => m.Status, new { @class = "control-label required" })
                    <div class="@divCss">
                        @Html.DropDownListFor(m => m.Status, new SelectList(Model.StatusList, "Value", "Text"), new { @class = @inputCss })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => m.Account, new { @class = "control-label" })
                    <div class="@divCss">
                        @Html.TextBoxFor(m => m.Account, new { @class = @inputCss })
                        @Html.ValidationMessageFor(m => m.Account)
                    </div>
                </div>
            }
        </div>
                
        <div role="tabpanel" class="tab-pane" id="divInfoSystem">
            @Html.Action("EditInfoSystem", "UserRegister", new { Id = Model.Id })
        </div>
        <div role="tabpanel" class="tab-pane" id="divSczi">
            <h3>Системные блоки</h3>
            @if (Model.Status == UserStatus.Work)
            {
                <p>
                    @Html.DialogFormButton(new DialogButtonOptions()
                        {
                                Text = "Добавить системный блок",
                                ContentUrl = Url.Action("AddUserPCDialog", "UserRegister", new { userId = Model.Id }),
                                Width = "800",
                                Id = "dlgAddUserPCDialog",
                                ButtonCss = "btn btn-large btn-primary",
                                OnSuccess = "RefreshPage",
                                ButtonId = "btnAddUserPC",
                                //UpdateTargetId = "divUserPC;divUserHistory",
                                //UpdateUrl = Url.Action("EditPC", "UserRegister", new { Id = Model.Id }) + ";" + Url.Action("UserHistory", "UserRegister", new { Id = Model.Id, historyGroup = (int)UserHistoryGroup.Scsi })
                        })
                </p>
            }
            <div id="divUserPC">
                @Html.Action("EditPC", "UserRegister", new { Id = Model.Id })
            </div>

            @if (IsUserInRole(new[] { UserRoles.Administrator.ToString(), UserRoles.UsersReestrSkziEditor.ToString(), UserRoles.UsersReestrSertificateEditor.ToString() }))
            {
            <h3>СКЗИ</h3>
            if ((Model.Status == UserStatus.Work) && (IsUserInRole(new[] { UserRoles.Administrator.ToString(), UserRoles.UsersReestrSkziEditor.ToString() })))
            {
                <p>
                    @Html.DialogFormButton(new DialogButtonOptions()
                        {
                                Text = "Добавить СКЗИ",
                                ContentUrl = Url.Action("AddUserSkziDialog", "UserRegister", new { userId = Model.Id }),
                                Width = "800",
                                Id = "dlgAddUserSkziDialog",
                                ButtonCss = "btn btn-large btn-primary",
                                OnSuccess = "RefreshUserSkzi",
                                ButtonId = "btnAddUserSkzi",
                                UpdateTargetId = "divUserPC;divUserSkzi;divUserHistory",
                                UpdateUrl = Url.Action("EditPC", "UserRegister", new { Id = Model.Id }) + ";" + Url.Action("EditSkzi", "UserRegister", new { Id = Model.Id }) + ";" + Url.Action("UserHistory", "UserRegister", new { Id = Model.Id, historyGroup = (int)UserHistoryGroup.Scsi })
                        })
                </p>
            }
            <div id="divUserSkzi">
                @Html.Action("EditSkzi", "UserRegister", new { Id = Model.Id })
            </div>
            }
        </div>
        @if (IsUserInRole(new[] { UserRoles.Administrator.ToString(), UserRoles.UsersReestrSkziEditor.ToString(), UserRoles.UsersReestrSertificateEditor.ToString() }))
        {
        <div role="tabpanel" class="tab-pane" id="divCert">
            @Html.Action("EditCert", "UserRegister", new { Id = Model.Id })
        </div>
        }
    </div>
    <hr/>
    <div>
        <button class="btn btn-primary" type="submit" id="btnSave">Сохранить</button>
        <button class="btn btn-default" type="button" onclick="goBack();" id="btnCancel">Отмена</button>
    </div>
    
</div>

@section History
{
    <div class="panel panel-default">
        <div class="panel-heading">
            <i class="fa fa-list-alt fa-fw"></i>
            История
        </div>
        <div class="panel-body" id="divUserHistory">
            @{Html.RenderAction("UserHistory", new { id = Model.Id, historyGroup = (int)UserHistoryGroup.Contact });}    
        </div>
    </div>
}

@section scripts
{
@Scripts.Render("~/bundles/gridlibrary")
<script type="text/javascript" src="@(Url.Content("~/Scripts/AjaxRequest.js"))"></script>    
<script type="text/javascript">

    $(document).ready(function () {
        $('#DepartmentId').change(function () {
            GetDepartmentAddress();
        });
        $('#btnSave').on('click', function () { SaveUser(); });

        @if (!Model.IsEdit)
        {
            <text>
            $('[data-toggle="tab"][href="#divInfoSystem"]').hide(0);
            $('[data-toggle="tab"][href="#divSczi"]').hide(0);
            $('[data-toggle="tab"][href="#divCert"]').hide(0);
            </text>
        }

        $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
            RefreshHistory();
        });

        if (location.hash) {
            $("a[href=" + location.hash.substring(0, location.hash.length - 1) + "]").tab("show");
        }
    });

    function SaveUser() {
        $("#formContactInfo").submit();
        return false;
    }

    function RefreshHistory() {
        var historyUrl = '@Url.Action("UserHistory", new { id = Model.Id })';
        historyUrl += '?historyGroup=' + GetHistoryGroup();
        $('#divUserHistory').load(historyUrl, function () {
        });
    }

    function RefreshPage() {
        location.reload();
    }
    
    function GetHistoryGroup() {
        var tabId = $("ul#userTabs li.active").attr('id');
        if (tabId == 'liContactInfo') {
            return '@(((int)UserHistoryGroup.Contact).ToString())';
        }
        else if (tabId == 'liInfoSystem') {
            return '@(((int)UserHistoryGroup.InfoSystem).ToString())';
        }
        else if (tabId == 'liSczi') {
            return '@(((int)UserHistoryGroup.Scsi).ToString())';
        }
        else if (tabId == 'liCert') {
            return '@(((int)UserHistoryGroup.Cert).ToString())';
        }
        else {
            return '@(((int)UserHistoryGroup.Contact).ToString())';
        }
    }
</script>
}